package com.chilly.other.jdk8.function;

import org.junit.Ignore;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * Java 8中函数式接口的基本使用
 * <p>
 * Created by Chilly Cui on 2021/1/6.
 */
public class FunctionTest {

    //四大核心函数式接口:模拟消费性接口 Consumer
    public void consumer(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    @Test
    @Ignore
    public void testConsumer() {
        consumer(100.0, new Consumer<Double>() {
            @Override
            public void accept(Double money) {
                System.out.println("costed money : " + money);
            }
        });
        //costed money : 100.0
    }

    @Test
    @Ignore
    public void testConsumerWithLambda() {
        //可简写为: consumer(100.0, m -> System.out.println("costed monery : " + m));
        consumer(100.0, (Double m) -> System.out.println("costed money : " + m));
        //costed money : 100.0
    }


    ////四大核心函数式接口:模拟断定性接口 Predicate
    public List<String> predicate(List<String> list, Predicate<String> p) {
        ArrayList<String> arrayList = new ArrayList<>();
        for (String s : list) {
            if (p.test(s)) {
                arrayList.add(s);
            }
        }
        return arrayList;
    }


    //未使用Lambd表达式
    @Test
    @Ignore
    public void testPredicate() {
        List<String> list = Arrays.asList("ab", "bc", "abc", "bcd", "abcd", "bcde");

        List<String> filterList = predicate(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("a");
            }
        });

        System.out.println(filterList); //[ab, abc, abcd]
    }

    //使用Lambd表达式
    @Test
    public void testPredicateWithLambda() {
        List<String> list = Arrays.asList("ab", "bc", "abc", "bcd", "abcd", "bcde");

        //可简写为: List<String> filterList = predicate(list, s -> s.contains("a"));
        List<String> filterList = predicate(list, (String s) -> s.contains("a"));
        System.out.println(filterList);
    }

}
